package com.example.happiness.controller.admin;

import com.example.happiness.pojo.Category;
import com.example.happiness.pojo.admindto.UcategoryDTO;
import com.example.happiness.result.Result;
import com.example.happiness.service.admin.AdminCategoryService;
import com.example.happiness.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.util.List;
import java.util.Set;
import java.util.UUID;

@Api(tags = "服务类型相关接口")
@Slf4j
@RestController
@RequestMapping("/admin/category")
public class AdminCategoryController {

    @Autowired
    AdminCategoryService categoryService;
    @Autowired
    AliOssUtil aliOssUtil;
    @Autowired
    RedisTemplate redisTemplate;

    @PostMapping("/addCategory")
    @ApiOperation("添加服务类型")
    public Result addCategory(@RequestBody Category category){
        CloseCache2("serve_*");
        categoryService.addCategory(category);
        return Result.success();
    }

    @GetMapping("/selectCategory")
    @ApiOperation("查询服务类列表")
    public Result<List<Category>> selectCategory(){
        List<Category> categories = categoryService.selectCategory();
        return Result.success(categories);
    }

    @DeleteMapping("/deleteCategory")
    @ApiOperation("删除服务类型")
    public Result deleteCategory(Integer cid){
        CloseCache2("serve_*");
        return categoryService.deleteCategory(cid);
    }

    @PostMapping("/updatestate")
    @ApiOperation("修改服务类型状态")
    public Result updatestate(@RequestBody UcategoryDTO ucategoryDTO){
        CloseCache2("serve_*");
        return categoryService.updatestate(ucategoryDTO);
    }

    @PostMapping("/testupload")
    public Result<String> testupload(MultipartFile file) throws Exception{
        String originalFilename = file.getOriginalFilename();
        String Filename = UUID.randomUUID().toString()+originalFilename.substring(originalFilename.lastIndexOf("."));
        String url = aliOssUtil.uploudFils(Filename, (FileInputStream) file.getInputStream());
        return Result.success(url);
    }

    private void CloseCache2(String pattern){
        Set keys = redisTemplate.keys(pattern);
        System.out.println(keys);
        redisTemplate.delete(keys);
    }
}
